<template>
  <div>
    <SearchForm
        @search="onSearch"
        @reset="onReset"
        :search-list="searchList" :search-params="searchParams">
    </SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-box">
          <el-table
              size="large"
              stripe
              border
              v-loading="loading"
              max-height="500px"
              :data="tableData"
              row-key="id"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.8)"
              @selection-change="onSelect"
            >
            <el-table-column
                label="ID"
                align="center"
                prop="id"
                width="50px"
            />
            <el-table-column
                label="姓名"
                align="center"
                prop="nickname"
                width="180px"
                :show-overflow-tooltip="true"
            />
            <el-table-column label="手机号码" align="center" prop="phone" width="120px"/>
<!--            邀请码-->
            <el-table-column label="邀请二维码" align="center" prop="invite_qr_code" width="120px">
              <template #default="scope">
                <el-image
                  style="width: 80px; height: 80px"
                  :src="scope.row.invite_qr_code"
                  :preview-src-list="[scope.row.invite_qr_code]"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="所属上级" align="center" width="180px">
              <template #default="scope">
                <template v-if="scope.row.parent">
                  <div>{{ scope.row.parent.nickname }}</div>
                  <el-tag
                    size="mini"
                    :type="getParentTypeTag(scope.row.parent.user_type)"
                  >
                    {{ getParentTypeLabel(scope.row.parent.user_type) }}
                  </el-tag>
                </template>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="用户类型" align="center" prop="user_type" width="120px">
              <template #default="scope">
                <el-select
                  :value="scope.row.user_type"
                  size="mini"
                  @change="(value) => handleUserTypeChange(scope.row, value)"
                  placeholder="请选择用户类型">
                  <el-option
                    v-for="item in userTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="状态" key="status" width="100px">
              <template #default="scope">
                <el-tag v-if="scope.row.status === CommonStatusEnum.ENABLE" type="success">启用</el-tag>
                <el-tag v-else type="danger">禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column
                label="创建时间"
                align="center"
                prop="create_time"
                width="180"
            />
            <el-table-column label="操作" fixed="right" width="200px">
              <template slot-scope="scope">
                <el-button type="text" @click="onEdit2(scope.row)">生成邀请码</el-button>
                <el-button type="text" @click="onEdit(scope.row)">编辑</el-button>
                <el-button type="text" style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <div class="page-box">
        <el-pagination
            background
            :current-page="pageNo"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSize"
            @size-change="changePageSize"
            @current-change="changePageNo"
        />
      </div>
    </div>

    <Add ref="addFormRef" @get-page="initData" />
    <!-- 切换用户类型弹窗 -->
    <el-dialog
      :visible.sync="userTypeDialogVisible"
      title="切换用户类型"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form :model="userTypeForm" label-width="80px">
        <el-form-item label="用户类型">
          <el-select v-model="userTypeForm.user_type" style="width: 100%" @change="onDialogUserTypeChange">
            <el-option
              v-for="item in userTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
            培训
          </el-select>
        </el-form-item>
        <el-form-item label="上级用户" v-if="parentUserOptions.length">
          <el-select v-model="userTypeForm.parent_user_id" style="width: 100%" filterable placeholder="请选择上级用户">
            <el-option
              v-for="item in parentUserOptions"
              :key="item.id"
              :label="item.nickname + '（' + getParentTypeLabel(item.user_type) + '）'"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userTypeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onUserTypeDialogConfirm" :loading="userTypeDialogLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import crud from "@/mixins/crud";
import { http } from "@/api";
import Add from "./add.vue";
import {CommonStatusEnum, CommonUserLevelEnum, CommonUserLevelParentEnum} from "@/utils/enum";
export default {
  name: "index",
  computed: {
    CommonStatusEnum() {
      return CommonStatusEnum
    },
    CommonUserLevelEnum() {
      return CommonUserLevelEnum
    }
  },
  components: {
    Add,
  },
  mixins: [crud],
  data() {
    return {
      request:http.user,
      userTypeOptions: [
        { label: '普通用户', value: CommonUserLevelEnum.NORMAL_USER },
        { label: '商家', value: CommonUserLevelEnum.BUSINESS },
        { label: '一级分销商', value: CommonUserLevelEnum.DISTRIBUTOR_LEVEL1 },
        { label: '二级分销商', value: CommonUserLevelEnum.DISTRIBUTOR_LEVEL2 },
      ],
      searchList: [
        {
          label: '姓名',
          prop: 'nickname',
          name: 'input',
          clearable: true
        },
        {
          label: '手机号',
          prop: 'phone',
          name: 'input',
          clearable: true
        },
        {
          label: '用户类型',
          prop: 'user_type',
          name: 'select',
          clearable: true,
          options: [
            { label: '普通用户', value: CommonUserLevelEnum.NORMAL_USER },
            { label: '商家', value: CommonUserLevelEnum.BUSINESS },
            { label: '一级分销商', value: CommonUserLevelEnum.DISTRIBUTOR_LEVEL1 },
            { label: '二级分销商', value: CommonUserLevelEnum.DISTRIBUTOR_LEVEL2 }
          ]
        },
        {
          label: '状态',
          prop: 'status',
          name: 'select',
          clearable: true,
          options: [
            { label: '启用', value: CommonStatusEnum.ENABLE },
            { label: '禁用', value: CommonStatusEnum.DISABLE }
          ]
        },
      ],
      searchParams: {
        nickname: '',
      },
      tableData: [

      ],
      userTypeDialogVisible: false,
      userTypeDialogLoading: false,
      userTypeForm: {
        id: null,
        user_type: null,
        parent_user_id: null
      },
      parentUserOptions: [],
    }
  },
  methods: {
    getParentTypeTag(type) {
      switch (type) {
        case CommonUserLevelEnum.NORMAL_USER:
          return 'info';
        case CommonUserLevelEnum.BUSINESS:
          return 'warning';
        case CommonUserLevelEnum.DISTRIBUTOR_LEVEL1:
          return 'success';
        case CommonUserLevelEnum.DISTRIBUTOR_LEVEL2:
          return 'primary';
        default:
          return 'info';
      }
    },
    getParentTypeLabel(type) {
      switch (type) {
        case CommonUserLevelEnum.NORMAL_USER:
          return '普通用户';
        case CommonUserLevelEnum.BUSINESS:
          return '商家';
        case CommonUserLevelEnum.DISTRIBUTOR_LEVEL1:
          return '一级分销商';
        case CommonUserLevelEnum.DISTRIBUTOR_LEVEL2:
          return '二级分销商';
        default:
          return '未知';
      }
    },
    handleUserTypeChange(row, value) {
      // 弹窗方式切换用户类型和上级用户
      this.userTypeForm = {
        id: row.id,
        user_type: value,
        parent_user_id: null
      };
      this.userTypeDialogVisible = true;
      this.loadParentUserOptions(value);
    },
    // 弹窗内用户类型切换
    onDialogUserTypeChange(val) {
      this.userTypeForm.parent_user_id = null;
      this.loadParentUserOptions(val);
    },
    // 加载上级用户选项
    async loadParentUserOptions(userType) {
      // 商家和一级分销商无需指定上级
      if (userType === CommonUserLevelEnum.BUSINESS || userType === CommonUserLevelEnum.DISTRIBUTOR_LEVEL1) {
        this.parentUserOptions = [];
        this.userTypeForm.parent_user_id = 0; // 清空之前选中的上级用户
        return;
      }

      // 普通用户可选的上级包含二级分销商和普通用户
      if (userType === CommonUserLevelEnum.NORMAL_USER) {
        try {
          const [res1, res2] = await Promise.all([
            http.user.list({ user_type: CommonUserLevelEnum.DISTRIBUTOR_LEVEL2 }),
            http.user.list({ user_type: CommonUserLevelEnum.NORMAL_USER })
          ]);
          const level2Users = res1.data || [];
          const normalUsers = res2.data || [];
          this.parentUserOptions = [...level2Users, ...normalUsers];
        } catch (e) {
          this.parentUserOptions = [];
        }
        return;
      }

      // 获取目标用户类型的上级类型
      const parentType = CommonUserLevelParentEnum[userType];
      if (!parentType) {
        this.parentUserOptions = [];
        return;
      }
      // 查询所有该类型的用户
      try {
        const res = await http.user.list({ user_type: parentType });
        this.parentUserOptions = res.data && res.data ? res.data : [];
      } catch (e) {
        this.parentUserOptions = [];
      }
    },
    // 弹窗确认
    async onUserTypeDialogConfirm() {
      this.userTypeDialogLoading = true;
      try {
        await http.user.update(this.userTypeForm.id, {
          user_type: this.userTypeForm.user_type,
          parent_user_id: this.userTypeForm.parent_user_id
        });
        this.$message.success('修改成功');
        this.userTypeDialogVisible = false;
        this.onSearch && this.onSearch();
      } catch (e) {
        this.$message.error('修改失败');
      } finally {
        this.userTypeDialogLoading = false;
      }
    },
    onEdit2(row) {
      this.loading = true
      http.user.getUserQrCode({
        user_id: row.id
      }).then(res => {
        this.$message.success('获取二维码成功')
        this.onSearch()
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
